package com.akk.module.hxt.service;

import com.akk.PayConstants;
import com.akk.module.hlbpay.util.HlbBeanUtils;
import com.akk.module.hxt.model.HxtOpenCardRequest;
import com.akk.module.hxt.model.HxtOpenCardResponse;
import com.akk.module.hxt.utils.HttpClientHelper;
import com.akk.module.hxt.utils.HttpResponse;
import com.akk.module.hxt.utils.MD5Util;
import com.akk.utils.IDUtils;
import com.akk.utils.RestResponse;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.apache.http.HttpStatus;
import org.junit.Test;
import com.akk.module.hxt.model.*;
import com.akk.module.hxt.utils.HxtUtils;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;



@Component
public class HxtService {


    public RestResponse openCardAPI(HxtOpenCardRequest request){
        request.setVersion(PayConstants.HXT_VERSION);
        request.setAgentId(PayConstants.HXT_AGENT_ID);
        request.setMerId(PayConstants.HXT_MER_ID);
        try {
            Map<String,Object> params = HlbBeanUtils.convertBean(request,new LinkedHashMap());
            params = HxtUtils.paraFilter(params);
            String prestr = HxtUtils.createLinkString(params);
            prestr += "&key=" + PayConstants.HXT_REQUEST_KEY;
            String str = MD5Util.MD5Encode(prestr, "UTF-8");
            params.put("sign", str.toUpperCase());
            String reqBody = JSON.toJSONString(params);
            HttpResponse result = HttpClientHelper.doHttp(PayConstants.HXT_OPEN_CARD_URL, HttpClientHelper.POST,
                    "utf-8", reqBody, "60000", "text/plain;charset=UTF-8",null);
            if (result.getStatusCode() == HttpStatus.SC_OK){
                Gson gson = new Gson();
                HxtOpenCardResponse response = gson.fromJson(result.getRspStr(), HxtOpenCardResponse.class);
                Map<String,Object> resultMap = HlbBeanUtils.convertBean(response,new LinkedHashMap());
                resultMap = HxtUtils.paraFilter(resultMap);
                String resStr = HxtUtils.createLinkString(resultMap);
                resStr += "&key=" + PayConstants.HXT_RESPONSE_KEY;
                String resSign = MD5Util.MD5Encode(resStr,"UTF-8").toUpperCase();
                if (response.getRespCode().equals("00")){
                    return RestResponse.build(response);
                } else if ("88".equals(response.getRespCode())) {
                    // token过期
                    return RestResponse.build(RestResponse.HXT_TOKEN_OVERDUE,"TOKEN认证过期");
                }
                return RestResponse.build(RestResponse.AVS_ERROR_CODE,response.getRespMsg(),response);
            }
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"开卡失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE,"开卡失败");
    }

    public RestResponse openCardQuery(OpenCardQueryRequest request) {
        request.setVersion(PayConstants.HXT_VERSION);
        request.setAgentId(PayConstants.HXT_AGENT_ID);
        request.setMerId(PayConstants.HXT_MER_ID);
        try {
            //2 进行排序
            Map<String, Object> sPara = HxtUtils.paraFilter(HlbBeanUtils.convertBean(request,new LinkedHashMap()));
            //拼接报文
            String prestr = HxtUtils.createLinkString(sPara);
            prestr += "&key=" + PayConstants.HXT_REQUEST_KEY;
            String str = MD5Util.MD5Encode(prestr, "UTF-8");
            request.setSign(str.toUpperCase());
            String reqBody = JSON.toJSONString(request);
            HttpResponse result = HttpClientHelper.doHttp(PayConstants.HXT_OPEN_CARD_QUERY_URL,
                    HttpClientHelper.POST, "utf-8", reqBody,
                    "60000", "text/plain;charset=UTF-8",null);
            if(result.getStatusCode()== HttpStatus.SC_OK){
                Gson gson = new Gson();
                OpenCardQueryResponse response = gson.fromJson(result.getRspStr(),OpenCardQueryResponse.class);
                if("00".equals(response.getRespCode())){
                    return RestResponse.build(response);
                }else if ("88".equals(response.getRespCode())) {
                    // token过期
                    return RestResponse.build(RestResponse.HXT_TOKEN_OVERDUE,"TOKEN认证过期");
                }else{
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE,response.getRespMsg());
                }
            }
            return  RestResponse.build(RestResponse.AVS_ERROR_CODE,"服务器繁忙");
        } catch (Exception e) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"开卡查询失败");
        }
    }

    public RestResponse sendSMS(SendSMSRequest request) {
        request.setAgentId(PayConstants.HXT_AGENT_ID);
        request.setVersion(PayConstants.HXT_VERSION);
        request.setMerId(PayConstants.HXT_MER_ID);
        try {
            //2 进行排序
            Map<String, Object> sPara = HxtUtils.paraFilter(HlbBeanUtils.convertBean(request,new LinkedHashMap()));
            //拼接报文
            String prestr = HxtUtils.createLinkString(sPara);
            prestr += "&key=" + PayConstants.HXT_REQUEST_KEY;
            String str = MD5Util.MD5Encode(prestr, "UTF-8");
            sPara.put("sign", str.toUpperCase());
            String reqBody = JSON.toJSONString(sPara);
            HttpResponse result = HttpClientHelper.doHttp(PayConstants.HXT_QPAY_CONSUMER_SMS_API_URL, HttpClientHelper.POST, "utf-8", reqBody,
                    "60000", "text/plain;charset=UTF-8",null);
            if(result.getStatusCode()== HttpStatus.SC_OK){
                Gson gson = new Gson();
                SendSMSResponse response = gson.fromJson(result.getRspStr(),SendSMSResponse.class);
                if("00".equals(response.getRespCode())){
                    System.out.println("发送交易短信OrderId："+request.getOrderId());
                    return RestResponse.build(response);
                }else if ("88".equals(response.getRespCode())) {
                    // token过期
                    return RestResponse.build(RestResponse.HXT_TOKEN_OVERDUE,"TOKEN认证过期");
                }else {
                        return RestResponse.build(RestResponse.AVS_ERROR_CODE,response.getRespMsg());
                }
            }
            return  RestResponse.build(RestResponse.AVS_ERROR_CODE,"服务器繁忙");
        } catch (Exception e) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"开卡查询失败");
        }
    }


    public RestResponse payment (PaymentRequest request) {
        request.setVersion(PayConstants.HXT_VERSION);
        request.setAgentId(PayConstants.HXT_AGENT_ID);
        request.setMerId(PayConstants.HXT_MER_ID);
        try {
            //2 进行排序
            Map<String, Object> sPara = HxtUtils.paraFilter(HlbBeanUtils.convertBean(request,new LinkedHashMap()));
            //拼接报文
            String prestr = HxtUtils.createLinkString(sPara);
            prestr += "&key=" + PayConstants.HXT_REQUEST_KEY;
            String str = MD5Util.MD5Encode(prestr, "UTF-8");
            request.setSign(str.toUpperCase());
            sPara.put("sign", str.toUpperCase());
            String reqBody = JSON.toJSONString(sPara);
            HttpResponse httpResponse = HttpClientHelper.doHttp(PayConstants.HXT_QPAY_CONSUMER_API_URL, HttpClientHelper.POST, "utf-8", reqBody,
                    "60000", "text/plain;charset=UTF-8",null);
            System.out.println(reqBody);
            if(httpResponse.getStatusCode()== HttpStatus.SC_OK){
                Gson gson = new Gson();
                PaymentResponse response = gson.fromJson(httpResponse.getRspStr(),PaymentResponse.class);
                if("00".equals(response.getRespCode())){
                    System.out.println("发送交易请求OrderId："+request.getOrderId());
                    return RestResponse.build(response);
                }else if ("88".equals(response.getRespCode())) {
                    // token过期
                    return RestResponse.build(RestResponse.HXT_TOKEN_OVERDUE,"TOKEN认证过期");
                }else{
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE,response.getRespMsg());
                }
            }
            return  RestResponse.build(RestResponse.AVS_ERROR_CODE,"服务器繁忙");
        } catch (Exception e) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"交易失败");
        }
    }


    public RestResponse PayOrderQuery(PayOrderQueryRequest request) {
        request.setMerId(PayConstants.HXT_MER_ID);
        try {
            Map<String, Object> sPara = HxtUtils.paraFilter(HlbBeanUtils.convertBean(request, new LinkedHashMap()));
            String prestr = HxtUtils.createLinkString(sPara);
            prestr += "&key" + PayConstants.HXT_REQUEST_KEY;
            String str = MD5Util.MD5Encode(prestr, "UTF-8");
            request.setSign(str.toUpperCase());
            String reqBody = JSON.toJSONString(request);
            System.out.println(reqBody);
            HttpResponse result = HttpClientHelper.doHttp(PayConstants.HXT_QPAY_CONSUMER_QUERY_API_URL, HttpClientHelper.POST, "utf-8", reqBody,
                    "60000", "text/plain;charset=UTF-8",null);
            if(result.getStatusCode()== HttpStatus.SC_OK){
                Gson gson = new Gson();
                PayOrderQueryResponse response = gson.fromJson(result.getRspStr(),PayOrderQueryResponse.class);
                if("00".equals(response.getRespCode())){
                    return RestResponse.build(response);
                }else{
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE,response.getRespMsg());
                }
            }
            return  RestResponse.build(RestResponse.AVS_ERROR_CODE,"服务器繁忙");
        } catch (Exception e) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"交易失败");
        }

    }



     public RestResponse withdrawQuery(WithdrawQueryRequest request) {
        request.setAgentId(PayConstants.HXT_AGENT_ID);
        request.setVersion(PayConstants.HXT_VERSION);
         request.setMerId(PayConstants.HXT_MER_ID);
         //2 进行排序
         Map<String, Object> sPara = null;
         try {
             sPara = HxtUtils.paraFilter(HlbBeanUtils.convertBean(request,new LinkedHashMap()));
             //拼接报文
             String prestr = HxtUtils.createLinkString(sPara);
             prestr += "&key=" + PayConstants.HXT_REQUEST_KEY;
             String str = MD5Util.MD5Encode(prestr, "UTF-8");
             sPara.put("sign",str.toUpperCase());
             String reqBody = JSON.toJSONString(sPara);
             HttpResponse result = HttpClientHelper.doHttp(PayConstants.HXT_QPAY_WITH_DRAW_QUERY_URL, HttpClientHelper.POST, "utf-8", reqBody,
                     "60000", "text/plain;charset=UTF-8",null);
             if(result.getStatusCode()== HttpStatus.SC_OK){
                 Gson gson = new Gson();
                 WithdrawQueryResponse response = gson.fromJson(result.getRspStr(),WithdrawQueryResponse.class);
                 if("00".equals(response.getRespCode())){
                     if("00".equals(response.getOrigRespCode())){
                         return RestResponse.build(response);
                     }else if ("88".equals(response.getRespCode())) {
                         // token过期
                         return RestResponse.build(RestResponse.HXT_TOKEN_OVERDUE,"TOKEN认证过期");
                     }else{
                         return RestResponse.build(RestResponse.AVS_ERROR_CODE,response.getOrigRespMsg());
                     }
                 }else{
                     return RestResponse.build(RestResponse.AVS_ERROR_CODE,response.getRespMsg());
                 }
             }
             return  RestResponse.build(RestResponse.AVS_ERROR_CODE,"服务器繁忙");
         } catch (Exception e) {
             return RestResponse.build(RestResponse.AVS_ERROR_CODE,"交易失败");
         }
     }


    private static Map<String, Object> paraFilter(Map<String, Object> sArray) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }

        for (String key : sArray.keySet()) {
            Object value = sArray.get(key);
            if (value == null || value.equals("")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }
}

